<?php

/**
 * @filename 合同管理
 */

namespace app\admin\controller;

use app\admin\model\Conlog;
use app\admin\model\ProjectUser;
use app\admin\model\Conmember;
use phpDocumentor\Reflection\DocBlock\Tags\Var_;
use think\Controller;
use app\admin\model\Project;
use app\admin\model\Contract;
use app\admin\model\OrderContract;
use app\admin\model\Company;
use app\admin\model\Member;
use think\Db;
use expand\BestSignDemo;


class Hetong extends Common
{
    private $cModel;   //当前控制器关联模型

    public function _initialize()
    {
        parent::_initialize();
        $this->cModel = new Contract;
    }
    //列表
    public function index()
    {
        $where = [];
        if (input('get._sort')){
            $order = explode(',', input('get._sort'));
            $order = $order[0].' '.$order[1];
        }else{
            $order = 'id desc';
        }
        $dataList = $this->cModel->where($where)->order($order)->paginate('', false, page_param());
        $this->assign('PstatusList', Pstatus());
        $this->assign('dataList', $dataList);
        return $this->fetch();
    }
    //新建
    public function create()  //暂未使用
    {
        if (request()->isPost()){
            $data = input('post.');
            if(!$data['title']){
                return ajaxReturn('合同名称必填');
            }
            if(!$data['fpages']){
                return ajaxReturn('合同页码必填');
            }
            if(!$data['file_base64'] || !$data['file_md5']){
                return ajaxReturn('请选择合同文件');
            }
            $Best_data = new BestSignDemo();
            $res = $Best_data->uploadContract(str_replace('data:application/pdf;base64,','',$data['file_base64']),$data['title'],$data['fpages'],$data['file_md5']);
            $fid = $res->data->fid;
            if(!$fid){
                return ajaxReturn($res->errmsg);
            }
            $data['status'] = 1;
            $data['fid'] = $fid;
            $result = $this->cModel->allowField(true)->save($data);
            if($result){
                return ajaxReturn('创建成功',url('Hetong/index'));
            }else{
                return ajaxReturn($this->cModel->getError());
            }
        }else{
            //项目
            $teModel = new Project();
            $ProjectList = $teModel->field('id,project_name')->where(['status'=>['neq',-1]])->select();

            $this->assign('ProjectList', $ProjectList);
            return $this->fetch('edit');
        }
    }

    //编辑
    public function edit($id)
    {
        if (request()->isPost()){
            $data = input('post.');
            if (count($data) == 2){
                foreach ($data as $k =>$v){
                    $fv = $k!='id' ? $k : '';
                }
                $result = $this->cModel->allowField(true)->save($data, $data['id']);
            }else{
                $result = $this->cModel->allowField(true)->save($data, $data['id']);
            }
            if ($result){
                return ajaxReturn(lang('action_success'), url('index'));
            }else{
                return ajaxReturn($this->cModel->getError());
            }
        }else{
            //项目
            $teModel = new Project();
            $ProjectList = $teModel->field('id,project_name')->where(['status'=>['neq',5]])->select();
            $data = $this->cModel->where(['id'=>$id])->find();

            $this->assign('data', $data);
            $this->assign('ProjectList', $ProjectList);
            return $this->fetch();
        }
    }
    //删除合同
    public function deleteht()
    {
        if (request()->isPost()){
            $id = input('id');
            if (isset($id) && !empty($id)){
                $id_arr = explode(',', $id);
                if (!empty($id_arr)){
                    foreach ($id_arr as $val){
                        $this->cModel->where('id='.$val)->delete();
                        //关联表数据
                    }
                    return ajaxReturn(lang('action_success'), url('index'));
                }else{
                    return ajaxReturn(lang('action_fail'));
                }
            }
        }
    }

    //会员合同
    public function melist(){
        $ocModel = new OrderContract();
        $pModel = new Project();
        $Member=new Member();
        $contractModel = new Contract();
        $where = [];
        if(input('project_id')){
            $cid=$contractModel->where(array('project_id'=>intval(input('project_id'))))->value('id');
            $where['cid'] = intval($cid);
        }

        if(isset($_GET['sign']) && input('get.sign') != -1){
            $where['sign'] = ['eq',input('get.sign')];
        }
        if(isset($_GET['status']) && input('get.status') != -1){
            $where['status'] = ['eq',input('get.status')];
        }

        if(input('get.search')){
            $wh['username']=['LIKE','%'.input('get.search').'%'];
            $data=$Member->where($wh)->select()->toArray();
            foreach ($data as $v){
                $id[]=$v['id'];
            }
            $where['user_id'] = ['in',$id];
        }
        if (input('get._sort')){
            $order = explode(',', input('get._sort'));
            $order = $order[0].' '.$order[1];
        }else{
            $order = 'a.id desc';
        }

        if(input('get.down')){
            $tableHeader = ['会员名称','合同名称','身份证号','金额'];
            $dataList = $ocModel->alias('a')->field('a.*,b.username,b.certificate')->where($where)->join('tf_member b','a.user_id = b.id')->order($order)->select();
            $data = [];
            foreach($dataList as $k=>$v){
                $data[$k]['usernmae'] =  $v['username'];
                $data[$k]['title'] =  $v['title'];
                $data[$k]['certificate'] =  $v['certificate'].' ';
                $data[$k]['money'] =  $v['money'];
            }
            ToPHPEXECL($tableHeader,$data,'会员列表');
        }

        $dataList = $ocModel->alias('a')->field('a.*,b.username,b.certificate')->where($where)->join('tf_member b','a.user_id = b.id')->order($order)->paginate('', false, page_param());
        $this->assign('dataList', $dataList);
        $projectList = $pModel->where(['status'=>['NOT IN',[0,5]]])->select()->toArray();
        $this->assign('projectList', $projectList);
        return $this->fetch();
    }

    //查看合同
    public function detail($id){
        $Best_data = new BestSignDemo();
        $ocModel = new OrderContract();
        $where = ['id'=>$id];
        $ContInfo = $ocModel->where($where)->find();
        if(empty($ContInfo['contract_id'])){
            $this->error('合同未生成');
        }
        $result2 = $Best_data->viewContract($ContInfo['contract_id'],$ContInfo['ssqaccount']);
        if($result2->errno == 0){
            header("Location: ".$result2->data->url);
        }else{
            $this->error($result2->errmsg);
        }
    }

    //下载合同
    public function dowonload($id)
    {
        $Best_data = new BestSignDemo();
        $ocModel = new OrderContract();
        $ocinfo = $ocModel->where(['id'=>$id])->find();
        if(empty($ocinfo['contract_id'])){
            return $this->error('合同编号不存在');
        }
        $url = $Best_data->downloadContract($ocinfo['contract_id']);
        header("Location: ".$url);
    }

    //撤销合同
    public function cancel($id){
        $Best_data = new BestSignDemo();
        $ocModel = new OrderContract();
        $ocinfo = $ocModel->where(['id'=>$id])->find();
        if(empty($ocinfo['contract_id'])){
            return ajaxReturn('合同编码不存在');
        }
        $res = $Best_data->cancelContract($ocinfo['contract_id']);
        if($res->errno == 0){
            $ocModel->where(['id'=>$id])->update(['sign'=>2]);
            return ajaxReturn('操作成功',url('Hetong/melist'));
        }else{
            return ajaxReturn($res->errmsg);
        }
    }

    //公司列表
    public function companylist(){
        $where = [];
        if (input('get._sort')){
            $order = explode(',', input('get._sort'));
            $order = $order[0].' '.$order[1];
        }else{
            $order = 'id desc';
        }
//        $commodel=new Company();
//        $dataList = $commodel->where($where)->order($order)->paginate('', false, page_param());
        $commodel=new ProjectUser();
        $where['id'] = ['not in',[1,9]];
        $where['status'] = 5;
        $where['safemobile'] ='YES';
        $dataList = $commodel->where($where)->order($order)->paginate('', false, page_param());
        $this->assign('dataList', $dataList);
        return $this->fetch();
    }
    //添加公司
    public function addcompany(){
        if (request()->isPost()){
            $data = input('post.');
            if(!$data['account']){
                return ajaxReturn('公司账号必填');
            }
            if(!$data['mobile']){
                return ajaxReturn('电话必填');
            }
            if(!$data['name']){
                return ajaxReturn('公司名称必填');
            }
            if(!$data['code']){
                return ajaxReturn('统一社会信用代码必填');
            }
            if(!$data['legalPerson']){
                return ajaxReturn('法人代表姓名必填');
            }
            if(!$data['legalPersonIdentity']){
                return ajaxReturn('法人代表身份证必填');
            }
            if(!$data['legalPersonMobile']){
                return ajaxReturn('法人代表手机号必填');
            }
            if(!$data['contactMobile']){
                return ajaxReturn('CA年检抽查手机必填');
            }
            $Best_data = new BestSignDemo();
            $account=$data['account'];

            if($account){
                $where['account'] = $account;
                $commodel=new Company();
                $v=$commodel->where($where)->find();
                if(!empty($v)){
                    return ajaxReturn('该账号已注册');
                }
            }

            $mobile=$data['mobile'];
            $name=$data['name'];
            $userType='2';
            $credential['regCode']=$data['code'];
            $credential['orgCode']=$data['code'];
            $credential['taxCode']=$data['code'];
            $credential['legalPerson']=$data['legalPerson'];
            $credential['legalPersonIdentity']=$data['legalPersonIdentity'];
            $credential['legalPersonIdentityType']='0';
            $credential['legalPersonMobile']=$data['legalPersonMobile'];
            $credential['contactMobile']=$data['contactMobile'];
            $applyCert='1';
            $res=$Best_data->regUser($account,$mobile, $name, $userType, $credential, $applyCert);
            $res=json_encode($res);
            $res=json_decode($res,true);
            if($res['errno']==0){
                $code['account'] =$account;
                $code['phone'] = $mobile;
                $code['name'] =$name;
                $code['code'] = $data['code'];
                $code['frname'] = $data['legalPerson'];
                $code['frid'] =$data['legalPersonIdentity'];
                $code['frphone'] = $data['legalPersonMobile'];
                $code['ccphone'] = $data['contactMobile'];
                $code['taskld'] =$res['data']['taskId'];
                $model=new Company();
                $rut=$model->insert($code);
                if($rut){
                    return ajaxReturn('注册成功',url('companylist'));
                }else{
                    return ajaxReturn('注册失败');
                }
            }
            if(!empty($res['errmsg'])){
                return ajaxReturn($res['errmsg']);
            }else{
                return ajaxReturn('公司参数错误');
            }
        }else{
            return $this->fetch('editcom');
        }
    }


    //删除公司
    public function deletecom()
    {
        if (request()->isPost()){
            $id = input('id');
            if (isset($id) && !empty($id)){
                $id_arr = explode(',', $id);
                if (!empty($id_arr)){
                    foreach ($id_arr as $val){
                        $model=new Company();
                        $model->where('id='.$val)->delete();
                        //关联表数据
                    }
                    return ajaxReturn(lang('action_success'), url('companylist'));
                }else{
                    return ajaxReturn(lang('action_fail'));
                }
            }
        }
    }

    //生成公司印章
    public function addstamp(){
        if (request()->isPost()){
            $id = input('id');
//            $model=new Company();
//            $data = $model->where("id=$id")->find(); // 实例化User对象
            $model = new ProjectUser();
            $data = $model->where(['id'=>$id])->find();
            $Best_data = new BestSignDemo();
            $account=$data['account'];
            $text='';
            $fontName='';
            $fontSize='';
            $fontColor='';
            $rut=$this->uploadimg($account);
            $rut='data:image/jpg;base64,'.$rut;
            if(!empty($rut)){
                $res=$Best_data->setimg($account,$text,$fontName,$fontSize,$fontColor);
                $res=json_encode($res);
                $res=json_decode($res,true);
                if($res['errno']==0){
                    $model->where(['id'=>$id])->update(['stamp_state'=>1]); //根据条件更新记录
                    return ajaxReturn('生成成功',url('companylist'));
                }else{
                    return ajaxReturn($res['errmsg']);
                }

            }
        }
    }
    //下载图片
    public function uploadimg($account=null){
        $Best_data = new BestSignDemo();
        $image_name='';
        $data=$Best_data->uploadimg($account,$image_name);
        $str=base64_encode($data);
        return $str;
    }


    //可视化合同
    public function crecontract(){
//        $commodel=new Company();
//        $comlist = $commodel->select();
//        $this->assign('comlist', $comlist);

        //修改项目方数据源
        $puModel = new ProjectUser();
        $comlist = $puModel->where(['safemobile'=>'YES','status'=>5,'id'=>['not in',[1,9]]])->select();
        $this->assign('comlist', $comlist);

        $promodel=new Project();
        $prolist = $promodel->where(['id'=>['not in',[10,14,28,31,45,52]]])->select();
        $this->assign('prolist', $prolist);
        return $this->fetch();
    }

    //合同坐标生成
    public function crecom(){
        if(request()->isPost()){
            $data=$_POST['data'];
            $account=$data['company_id'];
            $pdf=$data['pdfdata'];
            $pdf=base64_decode($pdf);
            $pdfname=$data['title'];
            $fpages=$data['pages'];
            $rus=$this->upload($pdf,$account,$pdfname,$fpages);
            $rus=json_encode($rus,true);
            $rus=json_decode($rus,true);
            $fid=$rus['data']['fid'];
            if($fid){
                $model=new Contract();
                $res['xmoney']= number_format(($data['money1']['x']/$data['width']),2);
                $res['ymoney']= number_format(($data['money1']['y']/$data['height']),2);
                $res['mpage']=$data['money1']['page'];
                $res['hz_x']= number_format(($data['bmoney1']['x']/$data['width']),2);
                $res['hz_y']= number_format(($data['bmoney1']['y']/$data['height']),2);
                $res['hz_page']=$data['bmoney1']['page'];
                $res['xtomoney']= number_format(($data['money2']['x']/$data['width']),2);
                $res['ytomoney']= number_format(($data['money2']['y']/$data['height']),2);
                $res['mtopage']=$data['money2']['page'];
                $res['hzto_x']= number_format(($data['bmoney2']['x']/$data['width']),2);
                $res['hzto_y']= number_format(($data['bmoney2']['y']/$data['height']),2);
                $res['hzto_page']=$data['bmoney2']['page'];
                $res['dxname']= number_format(($data['uz']['x']/$data['width']),2);
                $res['dyname']= number_format(($data['uz']['y']/$data['height']),2);
                $res['dpage']=$data['uz']['page'];
                $res['cxname']= number_format(($data['gz']['x']/$data['width']),2);
                $res['cyname']= number_format(($data['gz']['y']/$data['height']),2);
                $res['cpage']=$data['gz']['page'];
                $res['xname']= number_format(($data['username']['x']/$data['width']),2);
                $res['yname']= number_format(($data['username']['y']/$data['height']),2);
                $res['npage']=$data['username']['page'];
                $res['xcard']= number_format(($data['idcard']['x']/$data['width']),2);
                $res['ycard']= number_format(($data['idcard']['y']/$data['height']),2);
                $res['id_card']=$data['idcard']['page'];
                $res['title']=$pdfname;
                $res['account']=$account;
                $res['project_id']=$data['project_id'];
                $res['fpages']=$fpages;
                $res['expiretime']=strtotime($data['expiretime']);
                $res['fid']=$fid;
                $rut=$model->insert($res);

            }
            if($rut){
                return ajaxReturn('生成成功', url('index'));
            } else {
                return ajaxReturn('注册失败');
            }
        }
    }
    //上传合同
    public function upload($pdf=null,$account=null,$pdfname=null,$fpages=null){
        $Best_data = new BestSignDemo();
        $fdata =base64_encode($pdf);//文件数据，base64编码
        $fmd5 =md5($pdf);//'';//文件md5值
        $ftype ='PDF';//文件类型
        $res=$Best_data->uploadfile($account,$fdata,$fmd5,$ftype,$pdfname,$fpages);
        $res=json_decode($res,true);
        return $res;
    }


    //查看合同
    public function lookht(){
        if(request()->isAjax()){
            $Contract=new Contract();
            $id = input('id');
            $fid=$Contract->where(['id'=>$id])->value('fid');
            $Best_data = new BestSignDemo();
            $res = $Best_data->downhetong($fid);
            return ajaxReturn('OK',$res);
        }
    }
    //生成合同
    public function batchht(){
        if(request()->isAjax()){
            $conModel=new Contract();
            $OrderContract=new OrderContract();
            $id = input('id');
            $proid=$conModel->where(['id'=>$id])->value('project_id');
            $ConList=$conModel->where(['id'=>$id])->find()->toArray();
            $title=$ConList['title'];
//            $sql="select GROUP_CONCAT(project_id) as project_id,GROUP_CONCAT(id) as order_id,SUM(money) as money,uid from tf_order where status=2 and type=1 and project_id in ($proid) GROUP BY uid";
//            $sql = "select * from
//                    (select GROUP_CONCAT(project_id) as project_id,GROUP_CONCAT(id) as order_id,SUM(money) as money,uid from tf_order where status=2 and type=1 and project_id in ($proid) GROUP BY uid ) as res
//                    where order_id not in
//                    (select order_id from tf_order_contract where is_project_qy=1) limit 500";
            $sql="
            SELECT
                *
            FROM
                (
                SELECT
                    GROUP_CONCAT( tor.project_id ) AS project_id,
                    GROUP_CONCAT( tor.id ) AS order_id,
                    SUM( tor.money ) AS money,
                    uid
                FROM
                    tf_order tor INNER JOIN tf_member tm on tm.id=tor.uid
                WHERE
                    tor.STATUS = 2
                    AND tor.type = 1
                    and tm.is_check=1
                    AND tor.project_id IN ( $proid)
                GROUP BY
                    tor.uid
                ) AS res
            WHERE
                order_id NOT IN ( SELECT order_id FROM tf_order_contract WHERE is_project_qy = 1 )
                LIMIT 100
            ";
            $data=Db::query($sql);
            if (empty($data)) {
                $status = [
                    'issend' =>'1',
                ];
                $conModel->where(['id'=>$id])->update($status);
                ajaxReturn('未找到需要生成的数据',url('hetong/index'));
            }
            $OrderContract->where('contract_id',null)->delete();
            foreach ($data as $v){
//                sleep(0.01);//延时0.01秒执行
                $p_ids=[16,17];
                $p_ids_1=[30,35];
                if(in_array($v['project_id'],$p_ids)){
                    $v['money']=0.8*$v['money'];
                }
                if(in_array($v['project_id'],$p_ids_1)){
                    $v['money']=0.6*$v['money'];
                }

                $this->makeContract($v['project_id'],$v['order_id'],$v['money'],$v['uid'],$title,$id);
            }
//            return ajaxReturn('生成成功',url('hetong/index'));
            ajaxReturn('操作成功');

        }
    }
    //创建合同订单
    private function makeContract($id,$order_id,$money,$userid,$title,$cid){
        $ocModel = new OrderContract;
        $member=new Member();
        $is_check=$member->where(['id'=>$userid])->value('is_check');
        if($is_check!=1){
            return true;
        }
        $re=$ocModel->where(['project_id'=>$id,'user_id'=>$userid,'is_project_qy'=>1])->find();
        if(!empty($re)){
            return true;
        }
        $ocontract = [
            'project_id' => $id,
            'cid' => $cid,
            'money' => $money,
            'user_id'	=> $userid,
            'title'	=> $title,
            'order_id' => $order_id,
            'is_project_qy'=>1, // 项目债券权益
            'create_time' => time(),
            'date'=>date('Y-m-d')
        ];
        $id = $ocModel->insertGetId($ocontract);
        $contractId = $this->AddYuansu($cid,$userid,$money);
        $ssqmobile=$member->where(['id'=>$userid])->value('ssqmobile');
        $ocModel->where(['id'=>$id])->update(['contract_id'=>$contractId,'ssqaccount'=>$ssqmobile]);
        $ocModel->where('contract_id',null)->delete();
        return true;
    }
    //添加合同元素
    private function AddYuansu($cid,$userid,$money){
        $ocModel = new OrderContract;
        $cotModel = new Contract();
//        $Member = new Conmember();
        $Member = new Member();
        $project_model = new Project();
        $Best_data = new BestSignDemo();
        $Cinfo = $cotModel->where(['id'=>$cid])->find();
        $Pinfo = $project_model->where(['id'=>$Cinfo['project_id']])->find();
        $MemberInfo = $Member->where(['id'=>$userid])->find();
        //姓名
        $ADDdata[] = $Best_data->writeContent($Cinfo['npage'],$Cinfo['xname'],$Cinfo['yname'],$MemberInfo['username']);
        //身份证
        $p_ids=[6,9,19,25,27,54,55,56,57,58,59,60,61];
        if(in_array($Cinfo['project_id'],$p_ids)){
            $MemberInfo['certificate']='成都阿纳巴里影业有限公司';
            $new_money_1='91510100MA6CPMUL86';
        }else{
            $MemberInfo['certificate']='北京畅想新影影业有限公司';
            $new_money_1='91110105MA01D5EK5W';
        }

        $ADDdata[] = $Best_data->writeContent($Cinfo['id_card'],$Cinfo['xcard'],$Cinfo['ycard'],$MemberInfo['certificate']);
        //金额
//        $new_money_1='65121151541541545665465';
        $ADDdata[] = $Best_data->writeContent($Cinfo['mpage'],$Cinfo['xmoney'],$Cinfo['ymoney'],$new_money_1);
        //大写金额
        $new_money_2=$Pinfo['project_name'];
        $ADDdata[] = $Best_data->writeContent($Cinfo['hz_page'],$Cinfo['hz_x'],$Cinfo['hz_y'],$new_money_2);
        //金额2
        $ADDdata[] = $Best_data->writeContent($Cinfo['mtopage'],$Cinfo['xtomoney'],$Cinfo['ytomoney'],$money);
        //大写金额2
//        $ADDdata[] = $Best_data->writeContent($Cinfo['hzto_page'],$Cinfo['hzto_x'],$Cinfo['hzto_y'],rmb($money));

        $res = $Best_data->putContent($Cinfo['fid'],$ADDdata);
        $contractId = $Best_data->create($res->data->fid,$Cinfo['title'],$Cinfo['expiretime']);
        return $contractId;
    }


    //一键用户批量签署  用户签署
    public function usersign(){
        if(request()->isPost()){
            $id = input('id');
            $conModel=new Contract();
            $OrderContract=new OrderContract();
            $data=$OrderContract->where(['cid'=>$id,'issign'=>0])->limit(500)->select();
            $data= empty($data)?array():$data->toArray() ;
            if (empty($data)) {
                $status = [
                    'issend' =>'2',
                ];
                $conModel->where(['id'=>$id])->update($status);
                ajaxReturn('未找到需要签署的数据',url('hetong/index'));
            }
            foreach ($data as $v){
//                sleep(0.01);//延时0.01秒执行
                $this->signContract($v['user_id'],$id);
            }

//            return ajaxReturn('用户批量签署完成',url('hetong/index'));
            ajaxReturn('操作成功');
        }

    }
    //签署合同
    public function signContract($userid,$cid){
        $Best_data = new BestSignDemo();
        $cotModel = new Contract();
        $OrderContract=new OrderContract();

        $ContInfo = $OrderContract->where(['user_id'=>$userid,'cid'=>$cid])->find();
        $Cinfo = $cotModel->where(['id'=>$cid])->find();
        $position = [[
            'pageNum' => $Cinfo['dpage'],
            'x' => $Cinfo['dxname'],
            'y' => $Cinfo['dyname']
        ]];
        $result = $Best_data->signContract($ContInfo['contract_id'],$ContInfo['ssqaccount'],$position);

        if($result['errno'] == 0){
            $OrderContract->where(['user_id'=>$userid,'cid'=>$cid])->update(['sign'=>1,'issign'=>1]);
        }elseif ($result['errno'] == 241424){
            $OrderContract->where(['user_id'=>$userid,'cid'=>$cid])->update(['sign'=>1,'issign'=>1]);
        }

    }
    //公司一键批量签署  公司签章
    public function batchstamp(){
        if(request()->isPost()){
            $id = input('id');
            $Best_data = new BestSignDemo();
            $OrderContract=new OrderContract();
            $Contract=new Contract();
            $con=$Contract->where(['id'=>$id])->find()->toArray();
            $data=$OrderContract->where(['cid'=>$id,'sign'=>'1','iscon'=>0])->limit(500)->select();
            $data= empty($data)?array():$data->toArray() ;
            if (empty($data)) {
                $status = [
                    'issend' =>'3',
                ];
                $Contract->where(['id'=>$id])->update($status);
                ajaxReturn('未找到需要盖章的数据',url('hetong/index'));
            }
            $account=$con['account'];
            $position['0']['x']=$con['cxname'];
            $position['0']['y']=$con['cyname'];
            $position['0']['pageNum']=$con['cpage'];
            $position=json_encode($position);
            foreach ($data as $v){
//                sleep(0.01);//延时0.01秒执行
                $res=$Best_data->signContract($v['contract_id'],$account,$position);
                $sign = [
                    'sign' =>3,
                    'iscon' =>1
                ];
                if($res['errno']==0){
                    $OrderContract->where(['contract_id'=>$v['contract_id']])->update($sign);
                }elseif ($res['errno']==241424){
                    $OrderContract->where(['contract_id'=>$v['contract_id']])->update($sign);
                }
            }

//            return ajaxReturn('公司盖章完成',url('hetong/index'));
            ajaxReturn('操作成功');
        }
    }
    //发送合同
    public function sendht(){
         ajaxReturn('暂停发送');
        if(request()->isPost()){
            $id = input('id');
            $Contract=new Contract();
            $OrderContract=new OrderContract();
            $res=$OrderContract->where(['cid'=>$id,'sign'=>'3'])->update(['status'=>'1']);
            if($res){
                $Contract->where(['id'=>$id])->update(['issend' =>'4']);
                return ajaxReturn('合同发送完成',url('hetong/index'));
            }else{
                return ajaxReturn('合同发送失败');
            }
        }
    }
    //上上签用户注册
    public function userzc(){
        if(request()->isPost()){
            $id = input('user_id');
            $bestSign_demo = new BestSignDemo();
            $Member=new Member();
            $data=$Member->where(['id'=>$id])->find()->toArray();
            $mobile=$data['mobile'];
            $name=$data['username'];
            $credential['identity']=$data['certificate'];
            $user_type = "1";
            if(empty($data['ssqmobile'])){
                $account = $data['mobile'];
                $res = $bestSign_demo->regUser($account,$mobile, $name, $user_type, $credential,1);
                if($res->errno == 0){
                    $Member->where(['id'=>$id])->update(['ssqmobile'=>$account]);
                    return ajaxReturn('注册成功',url('hetong/melist'));
                }else{
                    return ajaxReturn('注册失败');
                }
            }
            $account=$data['ssqmobile'];
            $res = $bestSign_demo->regUser($account,$mobile, $name, $user_type, $credential,1);

            if($res->errno == 0){
                $Member->where(['id'=>$id])->update(['ssqmobile'=>$account]);
                return ajaxReturn('注册成功',url('hetong/melist'));
            }else{
                return ajaxReturn('注册失败');
            }
        }
    }

    //上上签用户补签
    public function userbq(){
        if(request()->isPost()){
            $cid=$_POST['cid'];
            $userid = input('user_id');
            $Best_data = new BestSignDemo();
            $cotModel = new Contract();
            $mModel = new Member();
            $OrderContract=new OrderContract();
            $ssqlmobile = $mModel->where(['id'=>$userid])->value('ssqmobile');
            $ContInfo = $OrderContract->where(['user_id'=>$userid,'cid'=>$cid])->find()->toArray();
            $Cinfo = $cotModel->where(['id'=>$cid])->find()->toArray();
            $position = [[
                'pageNum' => $Cinfo['dpage'],
                'x' => $Cinfo['dxname'],
                'y' => $Cinfo['dyname']
            ]];
            $result = $Best_data->signContract($ContInfo['contract_id'],$ssqlmobile,$position);

            if($result['errno'] == 0){
                $OrderContract->where(['user_id'=>$userid,'cid'=>$cid])->update(['sign'=>1,'date'=>date('Y-m-d'),'ssqaccount'=>$ssqlmobile,'issend'=>'1']);
                return ajaxReturn('补签成功',url('hetong/melist'));
            }
            return ajaxReturn('补签失败');

        }
    }


    //公司盖章
    public function comcre(){
        if(request()->isPost()){
            $contract_id=$_POST['contract_id'];
            $ocModel=new OrderContract();
            $oModel=new Contract();
            $data=$ocModel->where(['contract_id'=>$contract_id])->find()->toArray();
            $cid=$data['cid'];
            $rut=$oModel->where(['id'=>$cid])->find()->toArray();
            $account=$rut['account'];
            $position['0']['x']=$rut['cxname'];
            $position['0']['y']=$rut['cyname'];
            $position['0']['pageNum']=$rut['cpage'];
            $Best_data = new BestSignDemo();
            $position=json_encode($position);
            $res=$Best_data->signContract($contract_id,$account,$position);
            $res=json_encode($res);
            $res=json_decode($res,true);
            if($res['errno']==0){
                $ocModel->where(['contract_id'=>$contract_id])->update(['issend'=>'2','sign'=>'3']);
                return ajaxReturn('盖章成功',url('hetong/melist'));
            }else{
                return ajaxReturn('盖章失败');
            }
        }
    }
    //上上签用户补发
    public function userbf(){
        if(request()->isPost()){
            $OrderContract=new OrderContract();
            $contract_id=$contract_id=$_POST['contract_id'];
            $res=$OrderContract->where(['contract_id'=>$contract_id,'sign'=>'3'])->update(['status'=>'1','issend'=>'3']);
            if($res){
                return ajaxReturn('合同发送完成',url('hetong/melist'));
            }else{
                return ajaxReturn('合同发送失败');
            }
        }
    }

    //合同重发列表
    public function hetongcf()
    {
        $ocModel = new OrderContract();
        $pModel = new Project();
        $Member=new Member();
        $Contract=new Contract();
        $where['g.cf'] =['eq',1];
        if(isset($_GET['sign']) && input('get.sign') != -1){
            $where['g.sign'] = ['eq',input('get.sign')];
        }
        if(input('get.username')){
            $wh['username']=['LIKE','%'.input('get.username').'%'];
            $data=$Member->where($wh)->select()->toArray();
            foreach ($data as $v){
                $id[]=$v['id'];
            }
            $where['g.user_id'] = ['in',$id];
        }
        if(input('get.hetongname')){
            $where['g.title']=['LIKE','%'.input('get.hetongname').'%'];
        }
        if(input('get.certificate')){
            $user_id=$Member->where(['certificate'=>input('get.certificate')])->value('id');
            $where['g.user_id'] = ['eq',$user_id];
        }
        if (input('get.start_date') && input('get.end_date')){ // 开始/结束同时存在
            $start_date =input('get.start_date');
            $end_date = input('get.end_date');
            if($start_date==$end_date){
                $where['g.date'] = ['between time', [strtotime($start_date),strtotime($end_date.'+1 day')]];
            }else{
                $where['g.date'] = ['between time', [strtotime($start_date),strtotime($end_date)]];
            }

        }elseif(input('get.start_date')){
            $where['g.date'] = ['gt',input('get.start_date')];
        }elseif(input('get.end_date')){
            $where['g.date'] = ['lt',input('get.end_date')];
        }

        if (input('get.start_date') && input('get.end_date')){ // 开始/结束同时存在
            $start_date = input('get.start_date');
            $end_date = input('get.end_date');
            if($start_date==$end_date){
                $where['g.create_time'] = ['between time', [strtotime($start_date),strtotime($end_date.'+1 day')]];
            }else{
                $where['g.create_time'] = ['between time', [strtotime($start_date),strtotime($end_date)]];
            }

        }

        if (input('get._sort')){
            $order = explode(',', input('get._sort'));
            $order = $order[0].' '.$order[1];
        }else{
            $order = 'id desc';
        }
        $conlist=$Contract->select();
        $dataList =  $ocModel
            ->field('g.*,m.username,m.certificate')
            ->alias('g')
            ->join('tf_member m','g.user_id=m.id','LEFT')
            ->where($where)
            ->order($order)
            ->paginate('', false, page_param());
        $this->assign('dataList', $dataList);
        $this->assign('conlist', $conlist);
        $projectList = $pModel->where(['status'=>['NOT IN',[0,5]]])->select();
        $this->assign('projectList', $projectList);
        return $this->fetch();
    }

    public function hetongretry(){  // 合同重发新增
        $data = input('post.');
        $Member=new Member();
        $Conmember=new Conmember();
        $Contract=new Contract();
        $ocModel=new OrderContract();
        $Best_data = new BestSignDemo();
        $user=$Member->where(['username'=>$data['name'],'certificate'=>$data['idcards']])->find();
        if(empty($user)){
            return ajaxReturn('用户信息有误,请仔细检查用户信息');
        }
        $coninfo=$Contract->where(['id'=>$data['c_id']])->find()->toArray();
        $res=$this->AddcfYuansu($data['c_id'],$data['money'],$data['name'],$data['idcards']);
        $ocontract = [
            'project_id' => $coninfo['project_id'],
            'cid' => $data['c_id'],
            'money' => $data['money'],
            'user_id'	=> $user['id'],
            'title'	=> $coninfo['title'],
            'create_time' => time(),
            'date' => date('Y-m-d'),
            'contract_id'=>$res,
            'cf'=>1
        ];
        $fontName='';
        $fontSize='';
        $fontColor='';
        $rr=$Best_data->setimg($user['ssqmobile'],$data['name'],$fontName,$fontSize,$fontColor);
        if($rr->errno!=0){
            return ajaxReturn('上上签姓名生成失败');
        }
        $result=$this->usercf($coninfo['dpage'],$coninfo['dxname'],$coninfo['dyname'],$res,$user['ssqmobile']);  // 用户签
        if($result['errno'] == 0){
            $res=$this->comcf($coninfo['cxname'],$coninfo['cyname'],$coninfo['cpage'],$res,$coninfo['account']);  // 公司签
            if($res['errno']==0){
                $id = $ocModel->insertGetId($ocontract);

                $ocModel->where(['id'=>$id])->update(['sign'=>3,'status'=>'1','ssqaccount'=>$user['ssqmobile']]);
                $Conmember->where(['id'=>$user['id']])->update(['username'=>$data['name'],'certificate'=>$data['idcards']]);
                if(!$id){
                    return ajaxReturn('合同重发生成失败,请仔细检查');
                }
                $where=[
                    'cid'=>$data['c_id'],
                    'id'=>['NOT IN',$id],
                    'user_id'=>$user['id']
                ];
                $ocModel->where($where)->delete();
                return ajaxReturn('补发成功',url('hetong/hetongcf'));
            }else{
                return ajaxReturn('公司盖章失败,请仔细检查');
            }
        }else{
            return ajaxReturn('用户补签失败,请仔细检查');
        }
    }
    private function usercf($dpage,$dxname,$dyname,$res,$ssqmobile){
        $Best_data = new BestSignDemo();
        $positions = [[
            'pageNum' => $dpage,
            'x' => $dxname,
            'y' => $dyname
        ]];
        $result = $Best_data->signContract($res,$ssqmobile,$positions);
        return $result;
    }

    private function comcf($cxname,$cyname,$cpage,$res,$account){
        $Best_data = new BestSignDemo();
        $position['0']['x']=$cxname;
        $position['0']['y']=$cyname;
        $position['0']['pageNum']=$cpage;
        $position=json_encode($position);
        $res=$Best_data->signContract($res,$account,$position);
    }
    private function AddcfYuansu($cid,$money,$name,$idcards){
        $cotModel = new Contract();
        $Best_data = new BestSignDemo();
        $Cinfo = $cotModel->where(['id'=>$cid])->find();
        //姓名
        $ADDdata[] = $Best_data->writeContent($Cinfo['npage'],$Cinfo['xname'],$Cinfo['yname'],$name);
        //身份证
        $ADDdata[] = $Best_data->writeContent($Cinfo['id_card'],$Cinfo['xcard'],$Cinfo['ycard'],$idcards);
        //金额
        $ADDdata[] = $Best_data->writeContent($Cinfo['mpage'],$Cinfo['xmoney'],$Cinfo['ymoney'],$money);
        //大写金额
        $ADDdata[] = $Best_data->writeContent($Cinfo['hz_page'],$Cinfo['hz_x'],$Cinfo['hz_y'],rmb($money));
        //金额2
        $ADDdata[] = $Best_data->writeContent($Cinfo['mtopage'],$Cinfo['xtomoney'],$Cinfo['ytomoney'],$money);
        //大写金额2
        $ADDdata[] = $Best_data->writeContent($Cinfo['hzto_page'],$Cinfo['hzto_x'],$Cinfo['hzto_y'],rmb($money));

        $res = $Best_data->putContent($Cinfo['fid'],$ADDdata);
        $contractId = $Best_data->create($res->data->fid,$Cinfo['title'],$Cinfo['expiretime']);
        return $contractId;
    }

    /**
     *后台合同缩略图编辑修改
     * @author hey_heyang(635870453@qq.com)
     */
    public function contractLogoEdit(){
        $cModel = new Contract();
        if (request()->isAjax() && request()->isPost()) {
            $data['contract_id'] = trim($_POST['contract_id']);
            $data['logo'] = trim($_POST['logo']);
            $result = $cModel->where(array('id'=>$data['contract_id']))->update(array('logo'=>$data['logo']));
            if(!$result){
                ajaxReturn('缩略图更新失败');
            }else{
                ajaxReturn('更新成功',url('index'));
            }
        }else{
            if(empty($_GET['contract_id'])){
                ajaxReturn('合同id不能为空');
            }
            $data['contract_id'] = trim($_GET['contract_id']);
            $contract_info = $cModel->where($data)->find();
            $contract_info = empty($contract_info)?array():$contract_info->toArray();
            if(empty($contract_info)){
                ajaxReturn('未找到合同信息');
            }else{
                $contractInfo= $contract_info;
            }
            $this->assign('contractInfo', $contractInfo);
            return $this->fetch();
        }
    }


    /**
     *后台合同缩略图上传
     * @author hey_heyang(635870453@qq.com)
     */
    public function contractLogoUpload(){
        if (request()->isPost()) {
            $file = request()->file('imgFile');
            if ($file) {
                $dir = 'contract';
                $upload_res = companyUpload($file, $dir);
                $upload_res['fileName'] = str_replace('\\', '/', $upload_res['fileName']);
                if ($upload_res['status']) {
                    $data['logo'] = $upload_res['fileName'];
                    $data['logoSrc'] = '/uploads/contract/' . $upload_res['fileName'];
                    ajaxReturn('上传成功', 1, '', $data);
                } else {
                    ajaxReturn('上传失败');
                }

            } else {
                ajaxReturn('请选择文件');
            }
        }
    }


    /**
     *新生成合同流程
     */
    public function newContractBuild(){
        if (request()->isPost()) {
            $conModel=new Contract();
            $OrderContract=new OrderContract();
            $id = input('id');
            $proid=$conModel->where(['id'=>$id])->value('project_id');
            $ConList=$conModel->where(['id'=>$id])->find()->toArray();
            $title=$ConList['title'];
            $sql = "select * from
                    (select GROUP_CONCAT(project_id) as project_id,GROUP_CONCAT(id) as order_id,SUM(money) as money,uid from tf_order where status=2 and type=1 and project_id in ($proid) GROUP BY uid ) as res
                    where order_id not in
                    (select order_id from tf_order_contract) limit 100";
            $data=Db::query($sql);
            if (empty($data)) {
                $status = [
                    'issend' =>'1',
                ];
                $conModel->where(['id'=>$id])->update($status);
                ajaxReturn('未找到需要生成的数据',url('hetong/index'));
            }
            $OrderContract->where('contract_id',null)->delete();
            foreach ($data as $v){
                $Member = new Conmember();
                $MemberInfo = $Member->where(['id'=>$v['uid']])->find();
                $data_array['user_name1']=$MemberInfo['username'];
                $data_array['id_card']=$MemberInfo['certificate'];
                $data_array['money1_s']=$v['money'];
                $data_array['money1_l']=rmb($v['money']);
                $data_array['money2_s']=$v['money'];
                $data_array['money2_l']=rmb($v['money']);
                $this->newMakeContract($v['project_id'],$v['order_id'],$v['money'],$v['uid'],$title,$id,$ConList['fid'],$data_array);
            }
            ajaxReturn('操作成功');


        }
    }

    /**
     *新生成合同流程 生成合同
     */
    private function newMakeContract($id,$order_id,$money,$userid,$title,$cid,$fid,$data_array){
        $ocModel = new OrderContract;
        $Best_data = new BestSignDemo();
        $member=new Member();
        $is_check=$member->where(['id'=>$userid])->value('is_check');
        if($is_check!=1){
            return true;
        }
        $re=$ocModel->where(['project_id'=>$id,'user_id'=>$userid])->find();
        if(!empty($re)){
            return true;
        }
        $ocontract = [
            'project_id' => $id,
            'cid' => $cid,
            'money' => $money,
            'user_id'	=> $userid,
            'title'	=> $title,
            'order_id' => $order_id,
            'create_time' => time(),
            'date'=>date('Y-m-d')
        ];
        $id = $ocModel->insertGetId($ocontract);
        $res_data=$Best_data->createNewContract1($fid,$data_array);
        if($res_data['errno']===0){
            $token = $res_data['data']['templateToken'];
            $contract_res=$Best_data->createNewContract2($fid,$token,$title);
            if($contract_res['errno']===0){
                $contract_id=$contract_res['data']['contractId'];
                $ssqmobile=$member->where(['id'=>$userid])->value('ssqmobile');
                $ocModel->where(['id'=>$id])->update(['contract_id'=>$contract_id,'ssqaccount'=>$ssqmobile]);
            }
        }

        $ocModel->where('contract_id',null)->delete();
        return true;
    }

    /**
     *新生成合同流程  公司签章
     */
    public function newBatchStamp(){
        if(request()->isPost()){
            $id = input('id');
            $Best_data = new BestSignDemo();
            $OrderContract=new OrderContract();
            $Contract=new Contract();
            $con=$Contract->where(['id'=>$id])->find()->toArray();
            $data=$OrderContract->where(['cid'=>$id,'sign'=>'1','iscon'=>0])->limit(100)->select();
            $data= empty($data)?array():$data->toArray() ;
            if (empty($data)) {
                $status = [
                    'issend' =>'3',
                ];
                $Contract->where(['id'=>$id])->update($status);
                ajaxReturn('未找到需要盖章的数据',url('hetong/index'));
            }
            $account=$con['account'];
            $position['0']['x']=$con['cxname'];
            $position['0']['y']=$con['cyname'];
            $position['0']['pageNum']=$con['cpage'];
            $position=json_encode($position);
            foreach ($data as $v){
//                sleep(0.01);//延时0.01秒执行
                $res=$Best_data->signContract($v['contract_id'],$account,$position);
                $sign = [
                    'sign' =>3,
                    'iscon' =>1
                ];
                if($res['errno']==0){
                    $OrderContract->where(['contract_id'=>$v['contract_id']])->update($sign);
                }elseif ($res['errno']==241424){
                    $OrderContract->where(['contract_id'=>$v['contract_id']])->update($sign);
                }
            }

            ajaxReturn('操作成功');
        }
    }


    /**
     *新生成合同流程  用户签署
     */
    public function newUserSign(){
        if(request()->isPost()){
            $id = input('id');
            $conModel=new Contract();
            $OrderContract=new OrderContract();
            $data=$OrderContract->where(['cid'=>$id,'issign'=>0])->limit(100)->select();
            $data= empty($data)?array():$data->toArray() ;
            if (empty($data)) {
                $status = [
                    'issend' =>'2',
                ];
                $conModel->where(['id'=>$id])->update($status);
                ajaxReturn('未找到需要签署的数据',url('hetong/index'));
            }
            foreach ($data as $v){
                $this->signContract($v['user_id'],$id);
            }
            ajaxReturn('操作成功');
        }

    }





}